package org.example.skytool.wechat.login;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.example.annotation.LogTrace;
import org.example.exception.ParamLossErrorException;
import org.example.exception.ServerErrorException;
import org.example.skytool.commom.StringUtil;
import org.example.skytool.json.JackSonUtil;
import org.example.skytool.redis.RedisUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static org.example.skytool.redis.RedisConstants.*;

@Component
@Slf4j
public class WechatLoginUtil {

    @Resource
    private OkHttpClient okHttpClient;

    @Resource
    private RedisUtils redisUtils;

//    private final static String appid = "wxf01a5eb35ab85feb";
    private final static String appid = "wx786cc9bc52ccdde6";
//    private final static String secretId = "d6b1171e44c5d951b9de32ba60f11b2f";
    private final static String secretId = "a9c27c2b52fb8278088df797e439c090";

    public String getAccessToken(){
        if(redisUtils.hasKey(WECHAT_MOUDLE+WECHAT_ACCESS_CONTROLLER+WECHAT_ACCESS_TOKEN_KIND)){
            return redisUtils.stringGet(WECHAT_MOUDLE+WECHAT_ACCESS_CONTROLLER+WECHAT_ACCESS_TOKEN_KIND);
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        String appId = "appid=" + appid;
        String secret = "secret="+secretId;
        String grantType = "grant_type=client_credential";
        url = url + "?" + appId + "&" + secret + "&" + grantType;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            String json = response.body().string();
            WxAcToken wxAcToken = JackSonUtil.parse(WxAcToken.class,json);
            if(wxAcToken.getAccess_token()==null){
                throw new ServerErrorException("服务器错误！！！微信服务accesstoken获取失败");
            }
            redisUtils.stringSet(WECHAT_MOUDLE+WECHAT_ACCESS_CONTROLLER+WECHAT_ACCESS_TOKEN_KIND,wxAcToken.getAccess_token(),1L, TimeUnit.HOURS);
            return wxAcToken.getAccess_token();
        } catch (Exception e) {
            log.error("微信登录出大问题");
        }
        throw new ServerErrorException("服务器错误！！！微信服务accesstoken获取失败");
    }


    @LogTrace
    public String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String appId = "appid=" + appid;
        String secret = "secret="+secretId;
        String jsCode = "js_code=" + code;
        String grantType = "grant_type=authorization_code";
        url = url + "?" + appId + "&" + secret + "&" + jsCode + "&" + grantType;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            String json = response.body().string();
//            json = "{\"session_key\":\"UbQuY4hFryBLRESe9CMecQ==\",\"openid\":\"orh_B5cCk7m1tlqaSjUp5S3mBv-c\"}";
            System.out.println(json);
            WxLogin wxLogin = JackSonUtil.parse(WxLogin.class,json);

            if(StringUtil.isEmpty(wxLogin.getOpenid())){
                throw new ParamLossErrorException("大概率是传的code错误");
            }
            return wxLogin.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
               log.error("微信登录出大问题");
        }
        return "";
    }


}
